;;; init-vterm.el --- Configuration for vterm -*- lexical-binding: t -*-
;;; Commentary:
;;; Code:

(global-set-key [f2] #'vterm-toggle)
(global-set-key [C-f2] #'vterm-toggle-cd)
(global-set-key (kbd "M-q t") #'vterm-toggle)

(with-eval-after-load 'vterm
  (require 'vterm-toggle)
  (remove-hook 'kill-buffer-hook #'vterm-toggle--exit-hook)

  (defun ctrlwei/quit-vterm-window ()
    "Map key q to `ctrlwei/quit-window',
when vterm buffer process finished."
    (interactive)
    (if (get-buffer-process (buffer-name))
        (vterm-send "q")
      (ctrlwei/quit-window)))
  (define-key vterm-mode-map (kbd "q") #'ctrlwei/quit-vterm-window)

  (defun ctrlwei/vterm--sentinel (process event)
    "Sentinel of vterm PROCESS.
Argument EVENT process event."
    (let* ((buf (process-buffer process))
           (window (get-buffer-window buf 'visible)))
      (run-hook-with-args 'vterm-exit-functions
                          (if (buffer-live-p buf) buf nil)
                          event)
      (when (and vterm-kill-buffer-on-exit (buffer-live-p buf))
        (if window
            (ctrlwei/quit-window window)
          (kill-buffer buf)))))
  (advice-add 'vterm--sentinel :override #'ctrlwei/vterm--sentinel)

  (setq vterm-buffer-name-string "vterm %s")
  (add-to-list 'vterm-eval-cmds '("find-file-other-window" find-file-other-window))

  (define-key vterm-mode-map (kbd "M-q") nil)
  (define-key vterm-mode-map (kbd "M-q t")  #'vterm-toggle)
  (define-key vterm-mode-map (kbd "M-q q")  #'ctrlwei/quit-window)
  (define-key vterm-mode-map [(control return)] #'vterm-toggle-insert-cd)
  (define-key vterm-mode-map (kbd "M-n") #'vterm-toggle-forward)
  (define-key vterm-mode-map (kbd "M-p") #'vterm-toggle-backward))

(provide 'init-vterm)
;;; init-vterm.el ends here
